<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-content">
        <h2>使用清单</h2>
        <div class="header-actions">
          <el-button type="success" @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
          <el-button type="primary" @click="openAddDialog">
            <el-icon><Plus /></el-icon>
            新增使用记录
          </el-button>
        </div>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="材料名称">
          <el-input
            v-model="filterForm.materialName"
            placeholder="请输入材料名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="使用人">
          <el-input
            v-model="filterForm.userName"
            placeholder="请输入使用人"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="使用日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="使用类型">
          <el-select
            v-model="filterForm.usageType"
            placeholder="请选择类型"
            clearable
            style="width: 120px"
          >
            <el-option label="工单使用" value="work_order" />
            <el-option label="维护使用" value="maintenance" />
            <el-option label="其他使用" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadUsageRecords">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon color="#409eff"><Box /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.totalUsage }}</div>
              <div class="stats-label">总使用次数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon color="#67c23a"><Goods /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.totalMaterials }}</div>
              <div class="stats-label">涉及材料种类</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon color="#e6a23c"><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ stats.totalUsers }}</div>
              <div class="stats-label">使用人数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon">
              <el-icon color="#f56c6c"><Money /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-value">¥{{ stats.totalValue.toFixed(2) }}</div>
              <div class="stats-label">总使用价值</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 使用记录列表 -->
    <el-card class="table-card">
      <el-table
        :data="usageRecords"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="记录ID" width="80" />
        <el-table-column prop="material_code" label="材料编码" width="120" />
        <el-table-column prop="material_name" label="材料名称" min-width="150" />
        <el-table-column prop="specification" label="规格型号" min-width="120" />
        <el-table-column prop="quantity" label="使用数量" width="100">
          <template #default="{ row }">
            <span class="quantity-text">{{ row.quantity }} {{ row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unit_price" label="单价" width="100">
          <template #default="{ row }">
            ¥{{ row.unit_price?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="total_value" label="总价值" width="100">
          <template #default="{ row }">
            ¥{{ (row.quantity * (row.unit_price || 0)).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="usage_type" label="使用类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getUsageTypeColor(row.usage_type)">
              {{ getUsageTypeLabel(row.usage_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="user_name" label="使用人" width="100" />
        <el-table-column prop="usage_date" label="使用日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.usage_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="work_order_id" label="关联工单" width="100">
          <template #default="{ row }">
            <el-link
              v-if="row.work_order_id"
              type="primary"
              @click="viewWorkOrder(row.work_order_id)"
            >
              #{{ row.work_order_id }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="purpose" label="使用目的" min-width="150" show-overflow-tooltip />
        <el-table-column prop="notes" label="备注" min-width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editUsageRecord(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="deleteUsageRecord(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadUsageRecords"
          @current-change="loadUsageRecords"
        />
      </div>
    </el-card>

    <!-- 导出配置对话框 -->
    <el-dialog
      v-model="showExportDialog"
      title="导出配置"
      width="500px"
    >
      <el-form :model="exportForm" label-width="100px">
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportForm.format">
            <el-radio label="csv">CSV格式</el-radio>
            <el-radio label="excel">Excel格式</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="导出字段">
          <el-checkbox-group v-model="exportForm.fields">
            <div class="export-fields">
              <el-checkbox label="id">记录ID</el-checkbox>
              <el-checkbox label="material_code">材料编码</el-checkbox>
              <el-checkbox label="material_name">材料名称</el-checkbox>
              <el-checkbox label="specification">规格型号</el-checkbox>
              <el-checkbox label="quantity">使用数量</el-checkbox>
              <el-checkbox label="unit">单位</el-checkbox>
              <el-checkbox label="unit_price">单价</el-checkbox>
              <el-checkbox label="total_value">总价值</el-checkbox>
              <el-checkbox label="usage_type">使用类型</el-checkbox>
              <el-checkbox label="user_name">使用人</el-checkbox>
              <el-checkbox label="usage_date">使用日期</el-checkbox>
              <el-checkbox label="work_order_id">关联工单</el-checkbox>
              <el-checkbox label="purpose">使用目的</el-checkbox>
              <el-checkbox label="notes">备注</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="exportForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="文件名">
          <el-input v-model="exportForm.filename" placeholder="请输入文件名（不含扩展名）" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showExportDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmExport" :loading="exporting">
            确认导出
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/编辑使用记录对话框 -->
    <el-dialog
      v-model="showUsageDialog"
      :title="isEdit ? '编辑使用记录' : '新增使用记录'"
      width="600px"
    >
      <el-form
        ref="usageFormRef"
        :model="usageForm"
        :rules="usageRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="材料" prop="material_id">
              <el-select
                v-model="usageForm.material_id"
                placeholder="请选择材料"
                filterable
                style="width: 100%"
                @change="onMaterialChange"
              >
                <el-option
                  v-for="material in availableMaterials"
                  :key="material.id"
                  :label="`${material.name} (${material.code})`"
                  :value="material.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用数量" prop="quantity">
              <el-input-number
                v-model="usageForm.quantity"
                :min="1"
                :max="selectedMaterial?.stock_quantity || 999999"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="使用类型" prop="usage_type">
              <el-select v-model="usageForm.usage_type" style="width: 100%">
                <el-option label="工单使用" value="work_order" />
                <el-option label="维护使用" value="maintenance" />
                <el-option label="其他使用" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用人" prop="user_name">
              <el-input v-model="usageForm.user_name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="使用日期" prop="usage_date">
              <el-date-picker
                v-model="usageForm.usage_date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联工单">
              <el-input v-model="usageForm.work_order_id" placeholder="可选" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="使用目的" prop="purpose">
          <el-input v-model="usageForm.purpose" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="usageForm.notes" type="textarea" :rows="3" />
        </el-form-item>
        
        <div v-if="selectedMaterial" class="material-info">
          <h4>材料信息</h4>
          <el-descriptions :column="2" size="small" border>
            <el-descriptions-item label="材料编码">{{ selectedMaterial.code }}</el-descriptions-item>
            <el-descriptions-item label="规格型号">{{ selectedMaterial.specification }}</el-descriptions-item>
            <el-descriptions-item label="当前库存">{{ selectedMaterial.stock_quantity }} {{ selectedMaterial.unit }}</el-descriptions-item>
            <el-descriptions-item label="单价">¥{{ selectedMaterial.unit_price?.toFixed(2) || '0.00' }}</el-descriptions-item>
          </el-descriptions>
          <p class="total-value">
            预计使用价值：¥{{ ((usageForm.quantity || 0) * (selectedMaterial.unit_price || 0)).toFixed(2) }}
          </p>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showUsageDialog = false">取消</el-button>
          <el-button type="primary" @click="saveUsageRecord" :loading="saving">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import {
  Download,
  Plus,
  Search,
  Refresh,
  Box,
  Goods,
  User,
  Money
} from '@element-plus/icons-vue'
import { materialUsageApi } from '@/api'
import { materialsApi } from '@/api'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const exporting = ref(false)
const usageRecords = ref<any[]>([])
const availableMaterials = ref<any[]>([])
const selectedMaterial = ref<any>(null)

const filterForm = reactive({
  materialName: '',
  userName: '',
  dateRange: null as any,
  usageType: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const stats = reactive({
  totalUsage: 0,
  totalMaterials: 0,
  totalUsers: 0,
  totalValue: 0
})

// 导出功能相关
const showExportDialog = ref(false)
const exportForm = reactive({
  format: 'csv',
  fields: ['material_code', 'material_name', 'quantity', 'unit', 'usage_date', 'user_name'],
  dateRange: null as any,
  filename: '使用清单'
})

// 使用记录管理相关
const showUsageDialog = ref(false)
const isEdit = ref(false)
const usageFormRef = ref<FormInstance>()
const usageForm = reactive({
  material_id: '',
  quantity: 1,
  usage_type: 'work_order',
  user_name: '',
  usage_date: new Date().toISOString().split('T')[0],
  work_order_id: '',
  purpose: '',
  notes: ''
})

const usageRules = {
  material_id: [{ required: true, message: '请选择材料', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入使用数量', trigger: 'blur' }],
  usage_type: [{ required: true, message: '请选择使用类型', trigger: 'change' }],
  user_name: [{ required: true, message: '请输入使用人', trigger: 'blur' }],
  usage_date: [{ required: true, message: '请选择使用日期', trigger: 'change' }],
  purpose: [{ required: true, message: '请输入使用目的', trigger: 'blur' }]
}

// 方法
const loadUsageRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      per_page: pagination.size,
      material_name: filterForm.materialName,
      user_name: filterForm.userName,
      usage_type: filterForm.usageType,
      start_date: filterForm.dateRange?.[0],
      end_date: filterForm.dateRange?.[1]
    }
    
    const response = await materialUsageApi.getUsageRecords(params)
    usageRecords.value = response.data.records || []
    pagination.total = response.data.total || 0
    
    // 更新统计数据
    updateStats()
  } catch (error) {
    console.error('加载使用记录失败:', error)
    ElMessage.error('加载使用记录失败')
  } finally {
    loading.value = false
  }
}

const loadMaterials = async () => {
  try {
    const response = await materialsApi.getMaterials()
    availableMaterials.value = response.data.materials || []
  } catch (error) {
    console.error('加载材料列表失败:', error)
    ElMessage.error('加载材料列表失败')
  }
}

const updateStats = () => {
  stats.totalUsage = usageRecords.value.length
  stats.totalMaterials = new Set(usageRecords.value.map(r => r.material_code)).size
  stats.totalUsers = new Set(usageRecords.value.map(r => r.user_name)).size
  stats.totalValue = usageRecords.value.reduce((sum, record) => {
    return sum + (record.quantity * (record.unit_price || 0))
  }, 0)
}

const resetFilter = () => {
  Object.assign(filterForm, {
    materialName: '',
    userName: '',
    dateRange: null,
    usageType: ''
  })
  loadUsageRecords()
}

const getUsageTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    work_order: 'primary',
    maintenance: 'success',
    other: 'info'
  }
  return colorMap[type] || 'info'
}

const getUsageTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    work_order: '工单使用',
    maintenance: '维护使用',
    other: '其他使用'
  }
  return labelMap[type] || type
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const viewWorkOrder = (workOrderId: string) => {
  // 跳转到工单详情页面
  console.log('查看工单:', workOrderId)
}

// 导出功能方法
const exportData = () => {
  showExportDialog.value = true
}

const confirmExport = async () => {
  if (exportForm.fields.length === 0) {
    ElMessage.error('请至少选择一个导出字段')
    return
  }
  
  exporting.value = true
  
  try {
    // 准备导出数据
    let exportRecords = [...usageRecords.value]
    
    // 应用日期筛选
    if (exportForm.dateRange && exportForm.dateRange.length === 2) {
      const [startDate, endDate] = exportForm.dateRange
      exportRecords = exportRecords.filter(record => {
        const recordDate = record.usage_date
        return recordDate >= startDate && recordDate <= endDate
      })
    }
    
    // 准备导出内容
    const headers = exportForm.fields.map(field => getFieldLabel(field))
    const rows = exportRecords.map(record => {
      return exportForm.fields.map(field => {
        switch (field) {
          case 'total_value':
            return (record.quantity * (record.unit_price || 0)).toFixed(2)
          case 'usage_type':
            return getUsageTypeLabel(record.usage_type)
          case 'usage_date':
            return formatDate(record.usage_date)
          default:
            return record[field] || ''
        }
      })
    })
    
    // 生成文件内容
    let content = ''
    let filename = exportForm.filename || '使用清单'
    let mimeType = ''
    
    if (exportForm.format === 'csv') {
      content = [headers.join(','), ...rows.map(row => row.join(','))].join('\n')
      filename += '.csv'
      mimeType = 'text/csv;charset=utf-8;'
    } else {
      // Excel格式（简化为CSV）
      content = [headers.join(','), ...rows.map(row => row.join(','))].join('\n')
      filename += '.csv'
      mimeType = 'text/csv;charset=utf-8;'
    }
    
    // 下载文件
    const blob = new Blob([content], { type: mimeType })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', filename)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success(`成功导出 ${exportRecords.length} 条记录`)
    showExportDialog.value = false
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exporting.value = false
  }
}

const getFieldLabel = (field: string) => {
  const labelMap: Record<string, string> = {
    id: '记录ID',
    material_code: '材料编码',
    material_name: '材料名称',
    specification: '规格型号',
    quantity: '使用数量',
    unit: '单位',
    unit_price: '单价',
    total_value: '总价值',
    usage_type: '使用类型',
    user_name: '使用人',
    usage_date: '使用日期',
    work_order_id: '关联工单',
    purpose: '使用目的',
    notes: '备注'
  }
  return labelMap[field] || field
}

// 使用记录管理方法
const openAddDialog = () => {
  isEdit.value = false
  Object.assign(usageForm, {
    material_id: '',
    quantity: 1,
    usage_type: 'work_order',
    user_name: '',
    usage_date: new Date().toISOString().split('T')[0],
    work_order_id: '',
    purpose: '',
    notes: ''
  })
  selectedMaterial.value = null
  showUsageDialog.value = true
}

const editUsageRecord = (record: any) => {
  isEdit.value = true
  Object.assign(usageForm, {
    ...record,
    material_id: record.material_id || '1' // 模拟材料ID
  })
  
  // 设置选中的材料
  selectedMaterial.value = availableMaterials.value.find(m => m.id == usageForm.material_id)
  showUsageDialog.value = true
}

const onMaterialChange = () => {
  selectedMaterial.value = availableMaterials.value.find(m => m.id == usageForm.material_id)
}

const saveUsageRecord = async () => {
  if (!usageFormRef.value) return
  
  try {
    await usageFormRef.value.validate()
    
    if (!selectedMaterial.value) {
      ElMessage.error('请选择材料')
      return
    }
    
    if (usageForm.quantity > selectedMaterial.value.stock_quantity) {
      ElMessage.error('使用数量不能超过当前库存')
      return
    }
    
    saving.value = true
    
    const data = {
      material_id: usageForm.material_id,
      quantity: usageForm.quantity,
      usage_type: usageForm.usage_type,
      user_name: usageForm.user_name,
      usage_date: usageForm.usage_date,
      work_order_id: usageForm.work_order_id || null,
      purpose: usageForm.purpose,
      notes: usageForm.notes
    }
    
    if (isEdit.value) {
      await materialUsageApi.updateUsageRecord(usageForm.id, data)
      ElMessage.success('使用记录更新成功')
    } else {
      await materialUsageApi.createUsageRecord(data)
      ElMessage.success('使用记录创建成功')
    }
    
    showUsageDialog.value = false
    loadUsageRecords()
  } catch (error) {
    console.error('保存使用记录失败:', error)
    ElMessage.error('保存使用记录失败')
  } finally {
    saving.value = false
  }
}

const deleteUsageRecord = async (record: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条使用记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await materialUsageApi.deleteUsageRecord(record.id)
    ElMessage.success('使用记录删除成功')
    loadUsageRecords()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除使用记录失败:', error)
      ElMessage.error('删除使用记录失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadUsageRecords()
  loadMaterials()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  height: 100px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.stats-icon {
  font-size: 32px;
  margin-right: 15px;
}

.stats-info {
  flex: 1;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.quantity-text {
  font-weight: bold;
  color: #409eff;
}

.export-fields {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
  margin-top: 10px;
}

.material-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.material-info h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.total-value {
  margin-top: 10px;
  font-size: 16px;
  font-weight: bold;
  color: #e6a23c;
}

.dialog-footer {
  text-align: right;
}
</style>